from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
from matplotlib import pyplot as plt
import threading
import time
import random  


# A车间日生产货物数量
def A_save():
    global depot_initial_value
    while True:
        time.sleep(0.5)
        glock.acquire()    # 加锁
        A_save_num = random.randint(30,50)
        depot_initial_value += A_save_num
        glock.release()    # 释放锁

# B车间日生产货物数量
def B_save():
    global depot_initial_value
    while True:
        time.sleep(0.5)
        glock.acquire()    # 加锁
        B_save_num = random.randint(30,50)
        depot_initial_value += B_save_num
        glock.release()    # 释放锁

# 仓库日销售货量
def depot_out():
    global depot_initial_value
    while True:
        time.sleep(0.5)
        glock.acquire()    # 加锁
        depot_out_num = random.randint(80,100)
        depot_initial_value -= depot_out_num
        glock.release()    # 释放锁


if __name__ == '__main__':
    # 仓库货物数量的初始值
    depot_initial_value = 1000

    # 创建一个锁
    glock = threading.Lock()

    # 创建三个子进程来运行3个函数,并设置守护主线程
    A_thread = threading.Thread(target=A_save)
    A_thread.setDaemon(True) # 守护主线程
    B_thread = threading.Thread(target=B_save)
    B_thread.setDaemon(True) # 守护主线程
    out_thread = threading.Thread(target=depot_out)
    out_thread.setDaemon(True) # 守护主线程
    A_thread.start()
    B_thread.start()
    out_thread.start()

    # 主进程
    depot_initial_value_list =[depot_initial_value]
    y_list = range(0,1150,50)
    x_list = [0]
    fig = plt.figure(figsize=(16,6),dpi = 60)
    for i in range(1,31):
        time.sleep(0.49)
        plt.clf()
        print("第"+ str(i) + "天生产销售结束后的仓库货物数量：" + str(depot_initial_value))
        x_list.append(i)
        depot_initial_value_list.append(depot_initial_value)
        plt.plot(x_list, depot_initial_value_list)
        for a, b in zip(x_list, depot_initial_value_list):
            plt.text(a, b, b, ha='center', va='bottom', fontsize=20)
        plt.xticks(x_list,fontsize=10)
        plt.yticks( y_list,fontsize=10)
        plt.xlabel("天数", fontsize=20)
        plt.ylabel("货物数量", fontsize=20)
        plt.title("一个月内仓库货物数量变化情况", fontsize=20)
        plt.grid(alpha = 0.4,axis="both",linestyle="--",linewidth=1)
        plt.pause(0.01)
    plt.show()